/*!
 @header DynamicDetailViewController.m
 @author 周益
 @version 1.0.0 2013/02/02 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */

#import "DynamicDetailViewController.h"
#import "Helper.h"
#import <QuartzCore/QuartzCore.h>
#import "PersonalViewController.h"
#import "OrderConfirmViewController.h"
#import "MoodFormViewController.h"
#import "JMFBase.h"
#import "CellFactory.h"
#import "ReportingViewController.h"
#import "UIViewController+MJPopupViewController.h"
#import "HPGrowingTextView.h"
#import "MJRefresh.h"
#import "UMSocial.h"
#import "SocialDelegate.h"
#import "AppDelegate.h"
#import <TencentOpenAPI/TencentApiInterface.h>

//  -----------------------类详细介绍-----------------------
//
//  DynamicDetailViewController重点在于各种动态的显示以及Toolbar上显示的按钮的业务逻辑。
//     到动态详情页后，会有一个简单的流程：先请求此动态详情数据，根据此动态的类型（心情动态、商品动态和推荐动态）获取到动态发起者的id，
//        然后请求此用户的个人信息，通过用户的卖家服务等信息来判断toolbar上按钮的分布情况。
//
//  <功能描述>：动态的显示同商讯首页的动态显示，只是针对推荐详情中增加了商品详情的评论数、交易数和推荐数的显示。
//            同时在整个动态布局下面，挨着的时此动态的评论数。如果点击用户自己发的评论则是删除，如果点击的是其它用户的评论则是评论。
//
//  	<实现描述>：<#实现描述#>
//
//  	<注意事项>：<#注意事项#>
//
//  <功能描述>：Toolbar上显示的按钮的业务逻辑相对复杂。
//         功能阐述：
//            评论：评论此动态；
//            购买：如果是商品动态或者时推荐动态，那么就是购买此动态中的商品；
//            推荐：如果是商品动态或者时推荐动态，那么就是推荐此动态中的商品；
//            删除：删除此动态；
//
//         阐述4个按钮的存在条件：
//            评论：评论按钮是一直存在的；
//            购买：商品存在，商品未下架，商品不是用户自己的；如果是商品动态，动态创建者不是自己，如果是推荐动态，商品发布者不是自己；
//            推荐：不是心情动态，商品存在，商品未下架，TA是担保卖家，商品不是自己的；如果是推荐动态，那么商品发布者不是自己；
//            删除：必须时用户自己发的动态才能删除。
//
//         得到在toolbar上应该显示的按钮个数后，就对其布局，即给toolbar的按钮数组中插入填充对象。
//
//  	<实现描述>：<#实现描述#>
//
//  	<注意事项>：<#注意事项#>
//
//  <功能描述>：加载更多评论
//  	<实现描述>：持有一个BaseRefreshViewController实例替代继承UITableViewController，并且适应BaseRefreshViewControllerDelegate，
//                实现相应的代理方法，通过BaseRefreshViewController的实例变量去控制是否刷新或者是否是下拉刷新或者加载更多。
//  	<注意事项>：PersonalInfoViewController不能以tableview处理，所以就无法继承BaseRefreshViewController。
//                必须适应BaseRefreshViewControllerDelegate,并且持有BaseRefreshViewController一个实例。
//
//  点击了返回按钮后，会根据_disMode判断退出的方式，如果为true，那么推出VC时的方式为dismiss，否则为pop。
//
//  -----------------------类升级日志-----------------------
//
//  修改人   修改时间        修改描述              版本
//
// <#修改人#> <#修改时间#>    <#修改描述#>          <#版本#>

@interface DynamicDetailViewController ()<HPGrowingTextViewDelegate, MJRefreshBaseViewDelegate, UMSocialDataDelegate,UMSocialUIDelegate>

/*!
 @enum
 @abstract 用于鉴别toolbar上的用户操作，包括评论、购买、推荐和删除。
 @constant DynamicDetailDiscussEvent 0
 @constant DynamicDetailPurchaseEvent 1
 @constant DynamicDetailRecommendEvent 2
 @constant DynamicDetailDeleteEvent 3
 */
typedef NS_ENUM(NSInteger, DynamicDetailEvent) {
    DynamicDetailDiscussEvent,
    DynamicDetailPurchaseEvent,
    DynamicDetailRecommendEvent,
    DynamicDetailDeleteEvent,
    DynamicDetailFavoriteEvent
};
@end

@implementation DynamicDetailViewController
{
    UITableView *_tableView;
    UIView *_containerView;
    HPGrowingTextView *_textView;
    MJRefreshFooterView *_footer;
    MJRefreshHeaderView *_header;
}
@synthesize disMode = _disMode;
@synthesize delegate = _delegate;
@synthesize operateDelegate = _operateDelegate;
@synthesize orderId = _orderId;

/*!
 @abstract DynamicDetailViewController带参数的初始化方法
 @param dynamicID 动态ID
 @result InfoPickerViewController的实例
 */
- (id)initWithID:(NSInteger)dynamicID
{
    self = [super init];
    if (self) {
        _dynamicID = dynamicID;
        
        [[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(keyboardWillShow:)
													 name:UIKeyboardWillShowNotification
												   object:nil];
		
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(keyboardWillHide:)
													 name:UIKeyboardWillHideNotification
												   object:nil];
    }
    
    return self;
}

- (void)dealloc
{
    _dynamic = nil;
    [_commentsDataSource removeAllObjects];
    _commentsDataSource = nil;
    _userInfo = nil;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    //背景颜色
    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
    self.title = _L(@"vc_title_039");
    
    //返回按钮
    UIButton *backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, _SYS_FRAME_WIDTH, _SYS_FRAME_HEIGHT - 44 - 44) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundView = nil;
    [self.view addSubview:_tableView];

    //按钮的ToolBar
    _toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, _SYS_FRAME_HEIGHT - 44-44, 320, 44)];
    [_toolbar setBackgroundImage:[UIImage imageNamed:@"com_bg_005"] forToolbarPosition:UIToolbarPositionBottom barMetrics:UIBarMetricsDefault];

    // 4.3行集成上拉加载更多控件
    _footer = [MJRefreshFooterView footer];
    _footer.delegate = self;
    
    _commentsDataSource = [NSMutableArray new];
    
    //设置分享代理。
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    if (_parentDisFlag) {
        [_delegate closeViewController];
    }

}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self dynamicDetailinfoRequest];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the sectio
    return _commentsDataSource.count + 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    #warning: 这里要优化，使用静态的形式
    NSArray* Cellidentifiers = [NSArray arrayWithObjects:@"Cell_Info", @"Cell_Mood", @"Cell_Goods", @"Cell_Recommend", @"Cell_Comment", nil];
    UITableViewCell *cell;
    
    if (indexPath.row == 0) {
        cell = [tableView dequeueReusableCellWithIdentifier:[Cellidentifiers objectAtIndex:0]];
        if (cell == nil) {
            //获取复用对象
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[Cellidentifiers objectAtIndex:0]];
            [CellFactory makeCell:cell forName:NamedCellPersonInformationLight];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.backgroundColor = [UIColor whiteColor];
            cell.backgroundView.backgroundColor = [UIColor whiteColor];
        }
        
        [CellFactory drawCell:cell forName:NamedCellPersonInformation withDictionary:_dynamic];
    }
    else if (indexPath.row == 1) {
        NSInteger type = [_dynamic[@"type"] integerValue];
        
        //根据不同的动态类型，获取队列中的不同复用对象
        cell = [tableView dequeueReusableCellWithIdentifier:[Cellidentifiers objectAtIndex:type]];
        if (cell == nil) {
            
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[Cellidentifiers objectAtIndex:type]];
            [CellFactory makeCell:cell forName:type];
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.backgroundColor = [UIColor whiteColor];
            cell.backgroundView.backgroundColor = [UIColor whiteColor];
        }
        
        [CellFactory drawCell:cell forName:type withDictionary:_dynamic];
        
        //这里需要优化
        if (type == 3) {
            //商品信息footerview
            UIView* smallFooterView = [((UIView *)[cell.contentView.subviews objectAtIndex:2]).subviews objectAtIndex:7];
            smallFooterView.hidden = true;
        }
    }
    else{
        cell = [tableView dequeueReusableCellWithIdentifier:[Cellidentifiers objectAtIndex:4]];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[Cellidentifiers objectAtIndex:4]];
            [CellFactory makeCell:cell forName:NamedCellDynamicComment];
            cell.backgroundColor = [UIColor whiteColor];
            cell.backgroundView.backgroundColor = [UIColor whiteColor];
        }

        NSDictionary *dynamicComment = [_commentsDataSource objectAtIndex:[indexPath row] - 2];
        [CellFactory drawCell:cell forName:NamedCellDynamicComment withDictionary:dynamicComment];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}


#pragma mark - Table view delegate

//
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    float height = 0.0f;
    
    if (indexPath.row == 0){
        
        height = [CellFactory heightForName:NamedCellPersonInformation withDictionary:_dynamic];
    }
    else if (indexPath.row == 1) {
        
        height = [CellFactory heightForName:[_dynamic[@"type"] integerValue] withDictionary:_dynamic];
    }
    else {
        //根据内容动态设定高度
        NSDictionary *dynamicComment = _commentsDataSource[indexPath.row - 2];
        height = [CellFactory heightForName:NamedCellDynamicComment withDictionary:dynamicComment];
    }
    
    return height;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self recoverCommentView];
    
    if (indexPath.row == 0) {
        
        //获取动态发起人的personid
        NSInteger psersonId =  [_dynamic[@"creatorId"] integerValue];
        
        //跳转到个人信息页面
        PersonalInfoViewController *personalInfoVC = [[PersonalInfoViewController alloc] initWithPersonId:psersonId and:_dynamic[@"appKey"]];
        personalInfoVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:personalInfoVC animated:YES];
        
    }
    else if (indexPath.row > 1) {
        //获得被评论的row
        _rowIsSelected = indexPath.row - 2;
        
        //该评论的id
        _commentID = [_commentsDataSource[indexPath.row - 2][@"id"] integerValue];
        
        //该评论的发布者的id
        _userID = [_commentsDataSource[indexPath.row - 2][@"creatorID"] integerValue];
        
        UIActionSheet *actionSheet;
        //如果此评论是本人发的那么弹出来的actionsheet里面有删除此评论，无回复此评论，有取消
        if (_userID == [_ACCOUNT_ID integerValue]) {
            
            actionSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:_L(@"btn_no_01") destructiveButtonTitle:_L(@"btn_delete_04") otherButtonTitles:nil];   //删除该评论
            actionSheet.tag = 1;
            
            actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
            [actionSheet showInView:self.view];
        }
        //如果此评论不是本人的，那么actionsheet里面无删除评论，有回复此评论，无取消
        else{
            
            _commentSignal = NO;
            
            [self showCommentViewWithUserName:[NSString stringWithFormat:@"@%@",_commentsDataSource[indexPath.row - 2][@"creatorRealName"]]];

        }
     
    }
}


#pragma mark - 私有方法

/*!
 @abstract 通过用户id查询向服务器请求用户个人信息
 @param uid 用户id
 */
- (void)userInfoRequest:(NSString *)uid
{
    JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_U_GET_BASICINFO];
    request.delegate = self;
    [request setSuccessSelector:@selector(userInfoRequestSuccessSelector:)];
    [request setValue:uid forParameter:@"userId"];
    [request asynchronous];
}

/*!
 @abstract 通过checkid查询向服务器请求评论记录
 @param checkId 需要分页功能时，传入此id，即数据源中最后一条数据的ID
 */
- (void)commentsListRequestByCheckId:(NSString *)checkId
{
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_DYNAMIC_COMMENT_LIST];
    request.delegate = self;
    request.hudOn = true;
    [request setSuccessSelector:@selector(requestCommentSuccessSelector:)];
    request.hudTitle = _L(@"title_loading_01");
    [request setValue:[NSNumber numberWithInteger:_dynamicID] forParameter:@"dynamicId"];
    
    //id不为空，说明用户在加载更多
    if(checkId != nil){
        
        [request setValue:checkId forParameter:@"checkId"];
        [request setSuccessSelector:@selector(moreCommentsDidReceived:)];
    }
    
    [request asynchronous];
}

/*!
 @abstract 获取数据源最后一条数据的id
 @discussion 用于分页功能
 @result 数据源最后一条数据的id
 */
- (long)catchTheLastDataSourceId
{
    return [_commentsDataSource[_commentsDataSource.count - 1][@"id"] longValue];
}

/*!
 @abstract 根据业务显示此toolbar的功能按钮
 @result 组成toolbar
 */
- (NSMutableArray *)barButtonShouldShow
{
    //评论按钮
    _discussButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 55.0f, 29.0f)];
    [_discussButton setBackgroundImage:[UIImage imageNamed:@"transaction_btn_002_n"] forState:UIControlStateNormal];
    _discussButton.tag = DynamicDetailDiscussEvent;
    [_discussButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_discussButton setTitle:_L(@"btn_yes_08") forState:UIControlStateNormal];   //评论
    _discussButton.titleLabel.font = _SYS_FONT_004;
    [_discussButton addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
    
    //购买按钮
    _purchaseButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 55, 29)];
    _purchaseButton.tag = DynamicDetailPurchaseEvent;
    [_purchaseButton setBackgroundImage:[UIImage imageNamed:@"transaction_btn_002_n"] forState:UIControlStateNormal];
    [_purchaseButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_purchaseButton setTitle:_L(@"btn_yes_09") forState:UIControlStateNormal];   //购买
    _purchaseButton.titleLabel.font = _SYS_FONT_004;
    [_purchaseButton addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
    
    //推荐按钮
    _recommendButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 55, 29)];
    _recommendButton.tag = DynamicDetailRecommendEvent;
    [_recommendButton setBackgroundImage:[UIImage imageNamed:@"transaction_btn_002_n"] forState:UIControlStateNormal];
    [_recommendButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_recommendButton setTitle:_L(@"btn_yes_51") forState:UIControlStateNormal];   //推荐
    _recommendButton.titleLabel.font = _SYS_FONT_004;
    [_recommendButton addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
    
    //收藏按钮
    _favoriteButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 55, 29)];
    _favoriteButton.tag = DynamicDetailFavoriteEvent;
    [_favoriteButton setBackgroundImage:[UIImage imageNamed:@"transaction_btn_002_n"] forState:UIControlStateNormal];
    [_favoriteButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_favoriteButton setTitle:_L(@"btn_yes_32") forState:UIControlStateNormal];   //收藏
    _favoriteButton.titleLabel.font = _SYS_FONT_004;
    [_favoriteButton addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
    
    //利用fixedButton对齐
    _fixedButton  = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    NSMutableArray *toolBarButtons = [[NSMutableArray alloc] init];
    
    //此动态的发布者的用户ID
    NSInteger creatorId = [_dynamic[@"creatorId"] integerValue];
    
    //动态类型
    NSInteger type = [_dynamic[@"type"] integerValue];
    
    //推荐动态卖家id
    NSInteger sellerId = [_dynamic[@"sellerId"] integerValue];
    NSInteger sellerStatus = 0;  //默认为普通卖家
    
    if (_userInfo != nil) {
        //注意这里，卖家状态，是type，而且是TMD一个字符串
        sellerStatus = [_userInfo[@"sellerService"][@"type"] isEqualToString:_L(@"title_name_06")] ? 1 : 0;    //担保卖家
    }
    
    [toolBarButtons addObject:[[UIBarButtonItem alloc] initWithCustomView:_discussButton]];
    
    //购买按钮和收藏按钮存在的条件：商品存在，商品未下架，商品不是用户自己的；如果是商品动态，动态创建者不是自己，如果是推荐动态，商品发布者不是自己
    if (_dynamic[@"product"] != nil && ![_dynamic[@"product"] isKindOfClass:[NSNull class]] && [_dynamic[@"product"][@"status"] intValue] == 0) {
        
        if ((type == DynamicCategoryGoods && creatorId != [_ACCOUNT_ID integerValue]) || (type == DynamicCategoryRecommend && sellerId != [_ACCOUNT_ID integerValue])) {
            [toolBarButtons addObject:[[UIBarButtonItem alloc] initWithCustomView:_purchaseButton]];
        }
    }
    
    //推荐按钮存在的条件：不是心情动态，商品存在，商品未下架，TA是担保卖家，商品不是自己的；如果是推荐动态，那么商品发布者不是自己;逛一逛中去掉推荐按钮
    //商品存在
//    if ((_dynamic[@"product"] != nil && ![_dynamic[@"product"] isKindOfClass:[NSNull class]])
//        //且商品状态不是下架
//        && ([_dynamic[@"product"][@"status"] intValue] == 0)
//        //且卖家状态是担保卖家，发布者也不是自己
//        && sellerStatus == 1
//        
////        && creatorId != [_ACCOUNT_ID integerValue]
//        //逛一逛中去掉推荐按钮
//         && ([_dynamic[@"appKey"] isEqualToString:_CONFIG_APP_KEY])) {
//        
//        if ((type == DynamicCategoryGoods) || (type == DynamicCategoryRecommend)) {
////        if ((type == DynamicCategoryGoods) || (type == DynamicCategoryRecommend && sellerId != [_ACCOUNT_ID integerValue])) {
//            [toolBarButtons addObject:[[UIBarButtonItem alloc] initWithCustomView:_recommendButton]];
//        }
//    }
    //除开浏览者不是这个商品的卖家以及这个卖家不是担保卖家的情况，其它情况都存在分享按钮
    if (!(type == DynamicCategoryRecommend && sellerId != [_ACCOUNT_ID integerValue] && sellerStatus != 1) ||
         !(type == DynamicCategoryProduct && creatorId != [_ACCOUNT_ID integerValue] && sellerStatus != 1))
    {
        [toolBarButtons addObject:[[UIBarButtonItem alloc] initWithCustomView:_recommendButton]];
    }
    
    //购买按钮和收藏按钮存在的条件：商品存在，商品未下架，商品不是用户自己的；如果是商品动态，动态创建者不是自己，如果是推荐动态，商品发布者不是自己
    if (_dynamic[@"product"] != nil && ![_dynamic[@"product"] isKindOfClass:[NSNull class]] && [_dynamic[@"product"][@"status"] intValue] == 0) {
        
        if ((type == DynamicCategoryGoods && creatorId != [_ACCOUNT_ID integerValue]) || (type == DynamicCategoryRecommend && sellerId != [_ACCOUNT_ID integerValue])) {
            [toolBarButtons addObject:[[UIBarButtonItem alloc] initWithCustomView:_favoriteButton]];
        }
    }
    
    //按钮排序
    if (toolBarButtons.count == 1) {
        
        [toolBarButtons insertObject:_fixedButton atIndex:0];
        [toolBarButtons insertObject:_fixedButton atIndex:2];
    }
    
    else if(toolBarButtons.count == 2) {
        
        [toolBarButtons insertObject:_fixedButton atIndex:1];
        [toolBarButtons insertObject:_fixedButton atIndex:2];
    }
    
    else if(toolBarButtons.count == 3) {
        
        [toolBarButtons insertObject:_fixedButton atIndex:1];
        [toolBarButtons insertObject:_fixedButton atIndex:3];
    }
    
    else if(toolBarButtons.count == 4) {
        
        [toolBarButtons insertObject:_fixedButton atIndex:1];
        [toolBarButtons insertObject:_fixedButton atIndex:3];
        [toolBarButtons insertObject:_fixedButton atIndex:5];
    }
    else if (toolBarButtons.count == 5) {
        [toolBarButtons insertObject:_fixedButton atIndex:0];
        [toolBarButtons insertObject:_fixedButton atIndex:6];
    }
    return toolBarButtons;
}

/*!
 @abstract 根据动态ID请求动态详情信息
 */
- (void)dynamicDetailinfoRequest
{
    //获取动态信息
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_DYNAMIC_DETAILINFO];
    request.delegate = self;
    request.hudOn = true;
    request.hudTitle = _L(@"title_loading_01");
    
    //异步请求
    [request setValue:[NSString stringWithFormat:@"%d", _dynamicID] forParameter:@"dynamicId"];
    [request asynchronous];
}

//回复评论视图到默认状态
- (void)recoverCommentView
{
    [_textView resignFirstResponder];
    _textView.text = @"";
    _containerView.alpha = 0.0f;
}

//显示一个评论的视图
//name ： 需要显示评论的对象时，传递此参数
- (void)showCommentViewWithUserName:(NSString *)name
{
    if (_containerView != nil) {
        _containerView.alpha = 1.0f;
        _textView.alpha = 1.0f;
        UIButton *doneButton = (UIButton *)[_containerView viewWithTag:201];
        doneButton.enabled = NO;
        _textView.text = @"";

    }
    else {
        
        _containerView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 40, 320, 50)];
        _textView = [[HPGrowingTextView alloc] initWithFrame:CGRectMake(6, 12, 240, 30)];
        _textView.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);
        _textView.minNumberOfLines = 1;
        _textView.maxNumberOfLines = 6;
        _textView.layer.cornerRadius = 5.0f;

        _textView.returnKeyType = UIReturnKeyDefault; //just as an example
        _textView.font = _SYS_FONT_005;
        _textView.delegate = self;
        _textView.internalTextView.scrollIndicatorInsets = UIEdgeInsetsMake(5, 0, 5, 0);

        _textView.backgroundColor = [UIColor whiteColor];
        
        UIImage *rawBackground = [UIImage imageNamed:@"com_bg_015"];
        UIImage *background = [rawBackground stretchableImageWithLeftCapWidth:13 topCapHeight:22];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:background];
        imageView.frame = CGRectMake(0, 0, _containerView.frame.size.width, _containerView.frame.size.height);
        imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        
        _textView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        
        // view hierachy
        [_containerView addSubview:imageView];
        [_containerView addSubview:_textView];
        
        UIImage *sendBtnBackground = [[UIImage imageNamed:@"com_btn_42_n"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
        UIImage *selectedSendBtnBackground = [[UIImage imageNamed:@"com_btn_43_n"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
        
        UIButton *doneBtn = [[UIButton alloc] initWithFrame:CGRectMake(X_AND_WIDTH(_textView.frame)+8, 12, 54.5f, 32.5f)];
        doneBtn.tag = 201;
        doneBtn.enabled = NO;
        doneBtn.titleEdgeInsets = UIEdgeInsetsMake(2, 0, 0, 0);
        [doneBtn setTitle:_L(@"btn_yes_49") forState:UIControlStateNormal];
        doneBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
        doneBtn.titleLabel.font = _SYS_FONT_002;
        
        [doneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [doneBtn addTarget:self action:@selector(resignTextView) forControlEvents:UIControlEventTouchUpInside];
        [doneBtn setBackgroundImage:sendBtnBackground forState:UIControlStateNormal];
        [doneBtn setBackgroundImage:selectedSendBtnBackground forState:UIControlStateDisabled];
        [_containerView addSubview:doneBtn];
        _containerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    }
    
    //在这里添加原因：_containerView在隐藏后，需要重新设定视图层级关系
    [self.view insertSubview:_containerView aboveSubview:_tableView];
    if (name == nil || [name length] == 0) {
        
        _textView.placeholder = @"";
    }
    else {
        _textView.placeholder = name;
    }
    [_textView becomeFirstResponder];
}

//刷新tableview
- (void)reloadTableView
{
    [_tableView reloadData];
    // 结束刷新状态
    [_header endRefreshing];
    [_footer endRefreshing];
}

#pragma mark - 自定义事件

/*!
 @abstract 返回按钮事件
 */
- (void)backButtonEvent:(id)sender
{
    _parentDisFlag = true;
    [_operateDelegate dynamic:_dynamic operate:2];
    
    if (_disMode) {
        [self.navigationController dismissModalViewControllerAnimated:true];
    }
    else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

/*!
 @abstract toolbar上的用户操作，包括评论、购买、推荐和删除事件。
 */
- (void)buttonEvent:(id)sender
{
    UIButton *clickedButton = (UIButton *)sender;
    
    //评论按钮被点击
    if (clickedButton.tag == DynamicDetailDiscussEvent) {

        _commentSignal = YES;
        [self showCommentViewWithUserName:nil];
       
    //删除按钮被点击
    }else if(clickedButton.tag == DynamicDetailDeleteEvent){

    //购买按钮被点击
    }else if(clickedButton.tag == DynamicDetailPurchaseEvent){

        JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ORDER_ADD];
        [request setValue:[NSString stringWithFormat:@"%d", [_dynamic[@"product"][@"id"] integerValue]] forParameter:@"productId"];
        [request setValue:[NSString stringWithFormat:@"%d", _dynamicID] forParameter:@"dynamicId"];
        NSDictionary *responseData = [request synchronous];

        JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:responseData];
        
        if (jmf.status == JMStatusSucceed) {

            //此处要改，根据接口-建立订单改
            OrderConfirmViewController *orderConfirmVC = [[OrderConfirmViewController alloc] initWithDynamic:_dynamic];

            UINavigationController *orderConfirmNC = [[UINavigationController alloc] initWithRootViewController:orderConfirmVC];
            [Helper navigationControllerCommonStyle:orderConfirmNC];
            [orderConfirmVC.navigationItem setTitle:_L(@"vc_title_007")];
            
            [self.navigationController presentModalViewController:orderConfirmNC animated:YES];
        }
        else {
            [Helper easyShowJMFStatus:jmf];
        }
    }
    
    //收藏按钮被点击
    else if (clickedButton.tag == DynamicDetailFavoriteEvent) {
        
        JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_PRODUCT_PRODUCT_COLLECT_ADD];
        [request setValue:[NSString stringWithFormat:@"%d", [_dynamic[@"product"][@"id"] integerValue]] forParameter:@"productId"];
        [request setValue:[NSString stringWithFormat:@"%d", _dynamicID] forParameter:@"dynamicId"];
        NSDictionary *responseData = [request synchronous];
        
        JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:responseData];
        
        if (jmf.status == JMStatusSucceed) {
            
            [Helper showAllTextDialog:_L(@"alert_101") inSeconds:1.0f];
        }
        else {
            [Helper easyShowJMFStatus:jmf];
        }
    }
    
    //推荐按钮被点击
    else{
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        appDelegate.socialDelegate.dynamic = _dynamic;
        
        //自定义分享平台
        NSArray *shareToSnsNames = nil;
        
        //动态类型
        NSInteger type = [_dynamic[@"type"] integerValue];
        
        NSInteger sellerStatus = 0;  //默认为普通卖家
        
        if (_userInfo != nil) {
            //注意这里，卖家状态，是type，而且是TMD一个字符串
            sellerStatus = [_userInfo[@"sellerService"][@"type"] isEqualToString:_L(@"title_name_06")] ? 1 : 0;    //担保卖家
        }
        
        NSInteger sellerId = [_dynamic[@"sellerId"] integerValue];
        
        //此动态的发布者的用户ID
        NSInteger creatorId = [_dynamic[@"creatorId"] integerValue];
        
        //"我的圈子"存在条件：非心情动态、非逛一逛、浏览者是买家且卖家是担保卖家
        if (type != DynamicCategoryMood &&
            ([_dynamic[@"appKey"] isEqualToString:_CONFIG_APP_KEY]) &&
            ((type == DynamicCategoryRecommend && creatorId != [_ACCOUNT_ID integerValue] && sellerId != [_ACCOUNT_ID integerValue] && sellerStatus == 1) || (type == DynamicCategoryProduct && creatorId != [_ACCOUNT_ID integerValue] && sellerStatus == 1))
            ) {
            
            //分享到我的圈子
            __unsafe_unretained DynamicDetailViewController *sself = self;
            
            UMSocialSnsPlatform *sinaPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToFacebook];
            sinaPlatform.bigImageName = @"com_btn_044_n";
            sinaPlatform.displayName = _L(@"title_101");
            
            //点击后的事件
            sinaPlatform.snsClickHandler = ^(UIViewController *presentingController, UMSocialControllerService * socialControllerService, BOOL isPresentInController){
                
                MoodFormViewController* messageFormVC = [[MoodFormViewController alloc] init];
                messageFormVC.dynamicID = _dynamicID;
                messageFormVC.productID = [[[_dynamic valueForKey:@"product"] valueForKey:@"id"] intValue];
                messageFormVC.formType = MoodFormTypeRecommendProduct;
                
                UINavigationController* nc = [[UINavigationController alloc] initWithRootViewController:messageFormVC];
                
                [Helper navigationControllerCommonStyle:nc];
                
                [sself.navigationController presentModalViewController:nc animated:true];
                
            };
            
            shareToSnsNames = @[UMShareToFacebook,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToQQ,UMShareToQzone,UMShareToSina,UMShareToTencent];
        }
        else{
            shareToSnsNames = @[UMShareToWechatSession,UMShareToWechatTimeline,UMShareToQQ,UMShareToQzone,UMShareToSina,UMShareToTencent];
        }

        //手机QQ较特殊，需要先单独设置
        //分享链接
        NSString *url = [NSString stringWithFormat:_SYS_SHARE_PAGE,[_CONFIG_APP_KEY lowercaseString],[_dynamic[@"id"] integerValue]];
        //这里必须加上这一句，否则不传任何图片 友盟SDK就会默认分享的消息是文本，导致分享出去的商讯没有链接
        [UMSocialConfig setQQAppId:QQ_ID url:url importClasses:@[[QQApiInterface class],[TencentOAuth class]]];

        [UMSocialSnsService presentSnsIconSheetView:self appKey:_SYS_UMENG_APPKEY shareText:nil shareImage:nil shareToSnsNames:shareToSnsNames delegate:appDelegate.socialDelegate];
    }
}

#pragma mark - 更多按钮事件

- (void)moreButtonEvent:(id)sender
{
    UIActionSheet* actionSheet;
    
    //此动态的发布者的用户ID
    NSInteger creatorId = [_dynamic[@"creatorId"] integerValue];
    
    if (creatorId == [_ACCOUNT_ID integerValue]) {
        
        actionSheet = [[UIActionSheet alloc] initWithTitle:_L(@"alert_27") delegate:self cancelButtonTitle:_L(@"btn_no_01") destructiveButtonTitle:_L(@"btn_delete_06") otherButtonTitles:nil, nil];
        actionSheet.tag = 200;
    }
    else if (creatorId != [_ACCOUNT_ID integerValue] && [_userInfo[@"type"] intValue] == 2) {
        
        actionSheet = [[UIActionSheet alloc] initWithTitle:Nil delegate:(id)self cancelButtonTitle:_L(@"btn_no_01") destructiveButtonTitle:nil otherButtonTitles:_L(@"btn_yes_44"), nil];
        actionSheet.tag = 100;
    }
    
    [actionSheet showInView:self.view];
}


#pragma mark -
#pragma mark - ReportingViewControllerDelegate
 - (void)reportingViewControllerDidFinish
{
    [self dismissPopupViewControllerWithanimationType:MJPopupViewAnimationSlideLeftRight];
}

#pragma mark - JSONRequestDelegate

- (void)requestDidLoadJSON:(NSDictionary *)responseData
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:responseData];

    if (jmf.status == JMStatusSucceed) {

        _dynamic = jmf.data;
        _dynamicCategory = [jmf integerValue:@"type"];

        if (_dynamicCategory == DynamicCategoryGoods || _dynamicCategory == DynamicCategoryMood) {
            
            [self userInfoRequest:_dynamic[@"creatorId"]];
        }
        else if (_dynamicCategory == DynamicCategoryRecommend) {
            
            [self userInfoRequest:_dynamic[@"sellerId"]];
        }
        
        [self.view addSubview:_tableView];
        
        [_tableView reloadData];
        
        //载入评论
        if ([jmf integerValue:@"commentCount"] > 0) {
            
            [self commentsListRequestByCheckId:nil];
        }
        
        //从订单中来评论，就要默认弹出评论框
        if (_orderId != 0) {
            [self showCommentViewWithUserName:nil];
        }
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

//
- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}


- (void)requestCommentSuccessSelector:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];

    if (jmf.status == JMStatusSucceed) {

        if (_commentsDataSource.count != 0) {
            [_commentsDataSource removeAllObjects];
        }
        
        //将每次下拉刷新出的新数据都加入到数据源的最前面
        if ([(NSArray *)jmf.data count] != 0) {
            
            [_commentsDataSource addObjectsFromArray:(NSArray *)jmf.data];
            
            _footer.scrollView = _tableView;
        }
        if (_commentsDataSource.count > 0) {
            _tableView.tableFooterView.hidden = NO;
        }
        else {
            _tableView.tableFooterView.hidden = YES;
        }
        [self reloadTableView];
        
    }
    else {
        
        [Helper easyShowJMFStatus:jmf];
    }

}

- (void)moreCommentsDidReceived:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if ([(NSArray *)jmf.data count] != 0) {
            _tableView.tableFooterView.hidden = NO;
            [_commentsDataSource addObjectsFromArray:(NSArray *)jmf.data];
            
        }
        else{
            _tableView.tableFooterView.hidden = YES;
        }
        [self reloadTableView];
    }
    else {
        
        [Helper easyShowJMFStatus:jmf];
    }
}

- (void)userInfoRequestSuccessSelector:(NSDictionary *)dict
{
    
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        _userInfo = jmf.data;
        [_toolbar setItems:[self barButtonShouldShow]];
        [self.view addSubview:_toolbar];

        UIButton* moreButton = [Helper buttonWithStyle:ButtonStyleNavigationMore];
        [moreButton addTarget:self action:@selector(moreButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:moreButton];
        self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    }
    else {
        
        [Helper easyShowJMFStatus:jmf];
    }
}

#pragma mark - CloseControllerDelegate

- (void)closeViewController
{
    [self backButtonEvent:nil];
}

#pragma mark - UIActionSheet Delegate

//
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //tag等于1，表示点击的是删除该评论
    if (actionSheet.tag == 1 && buttonIndex == 0) {
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_28") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];   //您确定要删除此评论吗？
        
        alertView.tag = 50;
        [alertView show];
    }
    //tag = 2，是回复
    else if (actionSheet.tag == 2 && buttonIndex == 0) {

    }
    //更多按钮用的
    else if (actionSheet.tag == 100 && buttonIndex == 0) {
            
        ReportingViewController* reportingViewController = [[ReportingViewController alloc] initWithCategory:ReportingCategoryDynamic withID:[_dynamic[@"id"] longValue]];
        reportingViewController.delegate = (id)self;
        [self presentPopupViewController:reportingViewController animationType:MJPopupViewAnimationSlideLeftRight];
    }
    
    //确认是否删除动态
    else if (actionSheet.tag == 200 && buttonIndex == 0) {
        
        JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_DYNAMIC_REMOVE];
        [request setValue:[NSString stringWithFormat:@"%d", _dynamicID] forParameter:@"dynamicId"];
        NSDictionary *responseData = [request synchronous];
        
        JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:responseData];
        
        if (jmf.status == JMStatusSucceed) {
            //删除成功
            [self.operateDelegate dynamic:_dynamic operate:3];
            [self.navigationController popViewControllerAnimated:YES];
        }
        else {
            [Helper easyShowJMFStatus:jmf];
        }
    }
}

#pragma mark - UIAlertView Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //tag为50，则是用户点击的删除评论
    if (alertView.tag == 50) {
        
        if (buttonIndex == 0) {
            return;
        }
        
        JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_DYNAMIC_COMMENT_REMOVE];
        [request setValue:[NSString stringWithFormat:@"%d", _commentID] forParameter:@"commentId"];
        NSDictionary *responseData = [request synchronous];
        
        JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:responseData];
        
        if (jmf.status == JMStatusSucceed) {
            
            //删除评论后的动态评论的总条数
            [_commentsDataSource removeObjectAtIndex:_rowIsSelected];
            
            //            [_tableView reloadData];
            [self dynamicDetailinfoRequest];
        }
        else {
            [Helper easyShowJMFStatus:jmf];
        }
    }else{
        if (buttonIndex == 0) {
            return;
        }
    }
}

#pragma mark - CommentPubViewController Delegate

- (void)commentsShouldReload
{
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_DYNAMIC_COMMENT_LIST];
    request.delegate = self;
    [request setSuccessSelector:@selector(requestCommentSuccessSelector:)];
    [request setValue:[NSNumber numberWithInteger:_dynamicID] forParameter:@"dynamicId"];
    [request asynchronous];
}

#pragma mark -keyboard height control

//Code from Brett Schumann
-(void) keyboardWillShow:(NSNotification *)note{
    // get keyboard size and loctaion
	CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // Need to translate the bounds to account for rotation.
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
    
	// get a rect for the textView frame
	CGRect containerFrame = _containerView.frame;
    containerFrame.origin.y = self.view.bounds.size.height - (keyboardBounds.size.height + containerFrame.size.height);
	// animations settings
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
	
	// set views with new info
	_containerView.frame = containerFrame;
	
	// commit animations
	[UIView commitAnimations];
}

-(void) keyboardWillHide:(NSNotification *)note{
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
	
	// get a rect for the textView frame
	CGRect containerFrame = _containerView.frame;
    containerFrame.origin.y = self.view.bounds.size.height - containerFrame.size.height;
	
	// animations settings
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
	// set views with new info
	_containerView.frame = containerFrame;
	
	// commit animations
	[UIView commitAnimations];
}

//评论的发送按钮被点击
-(void)resignTextView
{
    [self commentPublishRequest];
}

//评论请求
- (void)commentPublishRequest
{
    
    JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_DYNAMIC_COMMENT_ADD];
    request.delegate = self;
    [request setSuccessSelector:@selector(commentDidPublished:)];
    [request setValue:[NSString stringWithFormat:@"%d", _dynamicID] forParameter:@"dynamicId"];
    [request setValue:_textView.text forParameter:@"content"];
    
    //从订单过来的评论要传入订单id
    if (_orderId != 0) {
        [request setValue:[NSString stringWithFormat:@"%d", _orderId] forParameter:@"productOrderId"];
    }
    
    //回复别人的评论要传得参数
    if (_userID != 0 && _commentID != 0 && !_commentSignal) {
        [request setValue:[NSString stringWithFormat:@"%d", _commentID] forParameter:@"replyCommentId"];
        [request setValue:[NSString stringWithFormat:@"%d", _userID] forParameter:@"replyUserId"];
        
    }
    
    [request asynchronous];
    
    [self recoverCommentView];
}

- (void)commentDidPublished:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_DYNAMIC_COMMENT_LIST];
        request.delegate = self;
        [request setSuccessSelector:@selector(requestCommentSuccessSelector:)];
        [request setValue:[NSNumber numberWithInteger:_dynamicID] forParameter:@"dynamicId"];
        [request asynchronous];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

#pragma mark - HPGrowingTextView Delegate

- (void)growingTextViewDidChange:(HPGrowingTextView *)growingTextView
{
    UIButton *doneButton = (UIButton *)[_containerView viewWithTag:201];
    if ([growingTextView.text length] > 0) {
        
        doneButton.enabled = YES;
    }
    else {
        doneButton.enabled = NO;
    }
    
}

- (void)growingTextView:(HPGrowingTextView *)growingTextView willChangeHeight:(float)height
{
    float diff = (growingTextView.frame.size.height - height);
    
	CGRect r = _containerView.frame;
    r.size.height -= diff;
    r.origin.y += diff;
	_containerView.frame = r;
}

#pragma mark - 刷新的代理方法---进入下拉刷新\上拉加载更多都有可能调用这个方法
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    //下拉刷新
    if (refreshView == _header) {
        
        //请求初始数据
//        [self commentsListRequestByCheckId:nil];
    }
    
    //上拉加载更多
    else {
        
        NSString *checkId = [NSString stringWithFormat:@"%ld", [self catchTheLastDataSourceId]];
        
        //发送加载更多的请求,数据接受成功后，设置_reloading
        [self commentsListRequestByCheckId:checkId];
    }
}

@end
